import pako from 'pako'
import base from '@/config/baseUrl';
const websocket = {
	state: {
		socketTask: null,
		is_open_socket: false
	},

  mutations: {
		CONTRACT_WEBSOCKET_INIT(state,url) {
			// 创建一个this.socketTask对象【发送、接收、关闭socket都由这个对象操作】
			state.socketTask = uni.connectSocket({
				url: url,
				success(data) {
					// console.log("websocket连接成功", data);
				},
			});
			// console.log('state.socketTask', state.socketTask)
			state.socketTask.onOpen((res) => {
				// console.log("火币USDT WebSocket连接正常打开中...！");
				state.is_open_socket = true;
        // todo 火币websocket 鉴权

        const moment = require('moment')
        // let signature = this.$u.func.get_sign('GET', base.huobi.url, '/linear-swap-notification', this.$u.func.get_body())
        /* let authData= {
          "op": "auth",
          
          "type": "api",
          
          "AccessKeyId": base.huobi.api_key,
          
          "SignatureMethod": "HmacSHA256",
          
          "SignatureVersion": "2",
          
          "Timestamp": moment.utc().format('YYYY-MM-DDTHH:mm:ss'),
          
          "Signature": signature,
          
          } */

          /* state.socketTask.send({
            data: authData,
            async success() {
              console.log("鉴权消息发送成功");
            },
          }) */

				
			})
			state.socketTask.onMessage((res) => {
			
				let ploydata = new Uint8Array(res.data);
				let msg = pako.inflate(ploydata, {to: 'string'});
				let result = JSON.parse(msg)
       
			
				if(result.ping){
					let data = {'pong': result.ping}
					state.socketTask.send({
						data: JSON.stringify(data),
						async success() {
							// console.log("pong消息发送成功");
						},
					});
					return
				} else {
          console.log('onMessage', result)
        }
				if(result.ch){
					console.log(result,"收到服务器内容：" + res);
					uni.$emit(result.ch,{data: result})
				}
				
			});
		},
		CONTRACT_WEBSOCKET_CLOSE(state){
			state.socketTask.close({
				success(res) {
					state.is_open_socket = false;
					console.log("关闭成功", res)
				},
				fail(err) {
					console.log("关闭失败", err)
				}
			})

		},
		
		CONTRACT_WEBSOCKET_SEND(state, p) {
			console.log("ws发送:", p);
			state.socketTask.send({
				data: p,
				async success() {
					//console.log("消息发送成功");
				},
			});
		}
	},

	actions: {
		CONTRACT_WEBSOCKET_INIT({
			commit
		}, url) {
			commit('CONTRACT_WEBSOCKET_INIT',url)
		},
		CONTRACT_WEBSOCKET_CLOSE({
			commit
		}){
			commit('CONTRACT_WEBSOCKET_CLOSE')
		},
		CONTRACT_WEBSOCKET_SEND({
			commit
		}, p) {
			commit('CONTRACT_WEBSOCKET_SEND', p)
		}
	}
}

export default websocket